<template>
  <div class="app-container">
    <!-- 添加或修改班级对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <el-form @submit.native.prevent ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="`${$branchName ? $branchName : '分院'}名称`"
              prop=""
            >
              {{ branchName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="`${$majorName ? $majorName : '专业'}名称`"
              prop=""
            >
              {{ majorName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          :label="`${$gradeName ? $gradeName : '班级'}名称`"
          prop="className"
        >
          <el-input
            style="width: 80%"
            v-model="form.className"
            :placeholder="`请输入${$gradeName ? $gradeName : '班级'}名称`"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item
          :label="`${$gradeName ? $gradeName : '班级'}简介`"
          prop="content"
        >
          <el-input
            style="width: 80%"
            maxlength="500"
            show-word-limit
            :rows="4"
            v-model="form.content"
            type="textarea"
            :placeholder="`请输入${$gradeName ? $gradeName : '班级'}简介`"
          />
        </el-form-item>

        <el-form-item label="封面" prop="classPic">
          <div>
            <!-- 上传图片 -->
            <div
              v-if="form.classPic"
              class="upload-head"
              @click="editCropper()"
            >
              <img v-bind:src="form.classPic" class="cover"/>
            </div>
            <div v-else class="upload-head" @click="editCropper()">
              <div>
                <img src="@/assets/images/add.png" class="add" alt="加载失败"/>
              </div>
              <div>上传图片</div>
            </div>

            <div class="text_tip">
              建议图片比例16:10，支持jpg、png格式，图片小于5M
            </div>
          </div>

          <vuecut
            :w="320"
            :h="200"
            :url="form.classPic"
            @coverResult="coverResult"
            title="图片上传"
            :open.sync="vuecutshow"
          ></vuecut>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="open = false">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitForm"
        >确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPost_class,
  delPost_class,
  addPost_class,
  updatePost_class
} from '@/api/schoolOrganization/organization'
import { checkIsUniqueClassName } from '@/api/major/major'

export default {
  name: 'Post',
  data() {
    return {
      branchId: '',
      majorName: '',
      branchName: '',
      vuecutshow: false,
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 总页数
      totalPage: 0,
      // 岗位表格数据
      postList: [],
      upLoadData: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // level
      level: [],
      // 查询参数
      activeIndex: '',
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        className: undefined,
        majorId: undefined
      },
      // 表单参数
      form: {
        majorId: undefined,
        classId: undefined,
        className: undefined,
        classPic: undefined,
        content: undefined
      },
      // 表单校验
      rules: {
        className: [
          {
            required: true,
            validator: this.checkClassName,
            trigger: 'blur'
          }
        ]
        // content: [{ required: true, message: "简介不能为空", trigger: "blur" }],
      }
    }
  },
  created() {

  },
  methods: {
    async checkClassName(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入班级名称'))
      } else {
        let params = {
          classId: this.form.classId,
          className: value
        }
        let res = await checkIsUniqueClassName(params)
        if (!res.data) {
          callback(new Error('班级名称已被使用'))
        } else {
          callback()
        }
      }
    },
    /** 组件返回图片 */
    coverResult(e) {
      this.form.classPic = e
    },
    editCropper() {
      this.vuecutshow = true
    },
    // 表单重置
    reset() {
      this.form = {
        majorId: undefined,
        classId: undefined,
        className: undefined,
        classPic: undefined,
        content: undefined
      }
      this.resetForm('form')
    },
    /** 新增按钮操作 */
    handleAdd(data) {
      this.reset()
      this.form.majorId = data.majorId
      this.branchId = data.branchId
      this.branchName = data.branchName
      this.majorName = data.majorName
      this.open = true
      this.title = `添加${this.$gradeName ? this.$gradeName : '班级'}`
    },
    /** 修改按钮操作 */
    handleUpdate(data) {
      this.reset()
      const postId = data.classId
      this.branchName = data.branchName
      this.majorName = data.majorName
      getPost_class(postId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = `修改${this.$gradeName ? this.$gradeName : '班级'}`
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.classId) {
            updatePost_class(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              let obj = {
                txt: 'edit',
                classId: this.form.classId,
                type: 'class'
              }
              this.$emit('refreshTreeData', obj)
            })
          } else {
            this.form.branchId = this.branchId
            addPost_class(this.form).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              let obj = {
                txt: 'add',
                type: 'class'
              }
              this.$emit('refreshTreeData', obj)
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(classId) {
      this.$confirm('是否确认删除？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        let res = await delPost_class(classId)
        if (res.code == 200) {
          this.$modal.msgSuccess('删除成功')
          let obj = {
            txt: 'del',
            type: 'class',
            classId: classId
          }
          this.$emit('refreshTreeData', obj)
        }
      }).catch(() => {
        this.$modal.msgInfo('已取消')
      })
    }
  }
}
</script>
<style scoped lang="scss">
// 上传图片样式
.text_tip {
  font-size: 12px;
  font-weight: 400;
  color: #a6a6a6;
}

.upload-head {
  cursor: pointer;
  position: relative;
  display: inline-block;
  width: 172px;
  height: 112px;
  border-radius: 4px;
  border: 1px dashed rgba(184, 196, 209, 1);

  .add {
    width: 29px;
    height: 29px;
    margin: 25px auto 0 auto;
  }

  div {
    font-size: 14px;
    font-weight: 400;
    color: rgba(153, 153, 153, 1);
    margin-top: 0;
    width: 100%;
    text-align: center;
  }

  .cover {
    width: 170px;
    height: 110px;
    border-radius: 4px;
  }
}
</style>
